from flask import Flask, render_template, request
import json
import requests
import csv

from common.common import output
from common.question import get_question
from common.token import get_access_token

# 修改成自己的api key和secret key
API_KEY = ""
SECRET_KEY = ""

app = Flask(__name__)

EB_INSTANT_URL = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token='

# 获取用户问题并返回结果
@app.route('/', methods=['GET', 'POST'])
# 调用大模型
def request_data():
    # getData = request.args.to_dict()  # 利用request对象获取GET请求数据
    question = request.args.get('question')
    if question is None:
        return render_template('page.html', content= "")  # 上传到html页面中
    else:
        if len(question) == 0:
            return render_template('page.html', content=question)  # 上传到html页面中
        else:
            url = EB_INSTANT_URL + get_access_token()
            # 调用大模型
            recommend = get_question(url, question)
            if recommend is None or '' ==  recommend:
                return render_template('page.html', content=question)  # 上传到html页面中

            file = open('csv/recommend.csv', 'w', encoding='UTF-8')
            file.write(recommend)
            file.close()
            # 运行output函数
            output()
            # 将处理好的数据上传到html
            with open('csv/boss.csv', 'r', encoding='UTF-8') as csvfile:
                reader = csv.reader(csvfile)
                result = list(reader)
                boss1 = ''.join(result[0])
                boss2 = ''.join(result[1])
                boss3 = ''.join(result[2])

            return render_template('page.html',
                                   content = question,
                                   reply = recommend,
                                   boss1=boss1,
                                   boss2=boss2,
                                   boss3=boss3)  # 上传到html页面中


if __name__ == '__main__':
    app.run(host="127.0.0.1", port=5000)
